import * as mobx from 'mobx';
import {observable, action, computed, asMap} from 'mobx';
import {WeaForm} from 'comsMobx';
import * as API from '../apis/api';
import findIndex from 'lodash/findIndex';
import concat from 'lodash/concat';
import dropWhile from 'lodash/dropWhile';
import * as Api from '../apis/communication';
import isFunction from 'lodash/isFunction';
import { message } from 'antd';
import { WeaLocaleProvider } from 'ecCom';
import cloneDeep from 'lodash/cloneDeep';
import { toJS } from 'mobx';
const getLabel = WeaLocaleProvider.getLabel;
export default class LogListStore {

    @observable loading = false;
    @observable searchForm = new WeaForm();
    refRequestId = 0; //相关请求ID
    @observable logListTabKey = 1; //tab页

    @observable isShowUserheadimg = true;

    @observable logList = [];
    logCount = 0;
    @observable logParams = {};
    requestLogParams = {}; //后台生成
    relLogParams = {};
    commonParams = {};

    //签字意见评论分页状态管理器
    @observable pageStatusMap = observable.map ? observable.map({}) : asMap({})
    @observable showSearchDrop = false;

    @observable appStatus = {}; //富文本是否允许上传附件，文档，关联流程。
    constructor() {
        this.initLog = this.initLog;
        this.loadLogBaseInfo = this.loadLogBaseInfo;
        this.loadMarkInfo = this.loadMarkInfo;
        this.updateLogParams = this.updateLogParams;
        this.changeLogListTab = this.changeLogListTab;
        this.controllShowUserImg = this.controllShowUserImg;
        this.loadRefReqSignInfo = this.loadRefReqSignInfo;
        this.scrollLoadSign = this.scrollLoadSign;
        this.controllSearchDrop = this.controllSearchDrop;
        this.clearFormFields = this.clearFormFields;
        this.setLogPagesize = this.setLogPagesize;
        this.advanceSearch = this.advanceSearch;

        //set
        this.setShowUserHeadImg = this.setShowUserHeadImg;
        this.setLoging = this.setLoging;
        this.setLogData = this.setLogData;
        this.setRequestLogParams = this.setRequestLogParams;
    }

    //获取签字意见参数
    @computed get queryLogParams() {
        return {isFromWfForm:1,...(this.logListTabKey > 2 ? this.relLogParams : this.logParams), ...this.searchForm.getFormParams()};
    }

    //设置主子流程名称连接信息
    @computed get logItemBaseParams() {
        return {
            'authStr': this.commonParams['authStr'],
            'authSignatureStr': this.commonParams['authSignatureStr'],
            'signatureAttributesStr': this.commonParams['signatureAttributesStr'],
            'signatureSecretKey': this.commonParams['signatureSecretKey'],
            'f_weaver_belongto_userid': this.commonParams['f_weaver_belongto_userid'],
            'f_weaver_belongto_usertype': this.commonParams['f_weaver_belongto_usertype'],
            'requestid': this.commonParams['requestid'],
            'workflowid': this.commonParams['workflowid'],
            'forward': this.commonParams['forward'],
            'isShowUserheadimg': this.isShowUserheadimg
        };
    }

    //获取当前第几页
    @computed get currentPage() {
        return this.logListTabKey > 2 ? this.relLogParams['pgnumber'] : this.logParams['pgnumber'];
    }

    @action initLog = (commonParams = {}) =>  {
        this.commonParams = commonParams;
        const baseParamKey = ["requestid", "requestType", "workflowid", "nodeid", "signatureAttributesStr", "signatureSecretKey", "f_weaver_belongto_userid",
            "f_weaver_belongto_usertype", "authStr", "authSignatureStr", "isprint", "wfTestStr", 'isurger'];
        this.relLogParams = {
            'signatureAttributesStr': commonParams['signatureAttributesStr'],
            'signatureSecretKey': commonParams['signatureSecretKey'],
            'f_weaver_belongto_userid': commonParams['f_weaver_belongto_userid'],
            'f_weaver_belongto_usertype': commonParams['f_weaver_belongto_usertype'],
            'wfTestStr': commonParams['wfTestStr'],
            "authStr" : commonParams['authStr'],
            "authSignatureStr" : commonParams['authSignatureStr'],
        };
        const logParams = {};
        baseParamKey.map(v => {
            logParams[v] = commonParams[v];
        });
        logParams['submit'] = commonParams.requestType;
        logParams['pgnumber'] = 1;
        logParams['maxrequestlogid'] = 0;
        this.logParams = logParams;
        this.loadLogBaseInfo();
        this.getAppStatus(this.logParams);

    }

    @observable communicateSettingKey  = {
      isShowSignCommunicate: '0',
      isExpendCommunicate: '0',
    };  //签字意见中关于交流的设置参数
    @action('加载签字意见权限相关')
    loadLogBaseInfo = () =>  {
        this.loading = true;
        const rightParamKey = ['viewLogIds', 'creatorNodeId', 'isHideInput', 'isFormSignature', 'maxrequestlogid', 'wfsignlddtcnt', 'orderbytype', 'logpagesize', 'loadmethod'];
        const communicateKey = ['isShowSignCommunicate', 'isExpendCommunicate'];
        API.getRequestLogBaseInfo(this.logListTabKey > 2 ? this.relLogParams : this.logParams).then((data) => {
            if (this.logListTabKey == 1) {
                this.setRequestLogParams(data);
                const {txStatus = '', logCondition} = data;
                this.searchForm.initFormFields(logCondition);
                this.setShowUserHeadImg(txStatus == '1');
            }
            let rightParams = {};
            rightParamKey.map(k => {
                rightParams[k] = data[k];
            });
            communicateKey.map( v => {
              if(data[v]) {
                this.communicateSettingKey[v] = data[v]
              }
            });
            this.updateLogParams(rightParams, true);
        });
    }

    @action('加载签字意见内容')
    loadMarkInfo = () =>  {
        if (!this.loading) this.setLoging(true);
        API.getRequestLogList(this.queryLogParams).then(data => {
            const {maxrequestlogid, totalCount, loglist} = data;
            this.updateLogParams({maxrequestlogid});
            this.setLogData(loglist, totalCount);
            this.setLoging(false);
            if (this.logParams.isprint && this.logParams.isprint == 1) {
                printPreViewPage();
            }
            this.getComment();
            this.refAppStatus({...this.logParams,isSubReqeuestid:this.isSubReqeuestid(),refRequestId:this.refRequestId});
        });
    }

    @observable hasSubmitRight = false; //交流是否有提交的权限
    @action('获取富文本相关底部设置项')
    getAppStatus = (params={}) => {
        Api.getInitParams(params).then(data => {
            this.appStatus = data.appStatus;
            this.hasSubmitRight = data.hasSubmitRight;
        })
    }

    @action('刷新当前tab页的appstatus')
    refAppStatus = (params={}) => {
        Api.getInitParams(params).then(data => {
            this.appStatus = data.appStatus;
        })
    }

    @action('加载签字意见评论内容')
    getComment = (params) => {
      const baseParamKey = ["requestid", "workflowid", "f_weaver_belongto_userid",
      "f_weaver_belongto_usertype", "authStr", "authSignatureStr", 'isurger'];
      let passParams = {};
      baseParamKey.map(v => {
        passParams[v] = this.logParams[v];
      });
      this.logList.map( (v,index) => {
        passParams = {...passParams, type: 'list', 
        requestLogId: v.logid,
        'refRequestId':this.refRequestId,
        'isSubReqeuestid':this.isSubReqeuestid(),
        ...this.queryLogParams
      };
        if(v.hasCommunicationQuote) {
          Api.getContentList(passParams).then( data => {
            const { contentList } = data;
            this.logList[index] = {...v, commentList: contentList};
           
          })
        }
      });
    }

    @action('改变分页状态管理器')
    changePageStatus = (id, currentPage) => {
      let pageStatus = this.pageStatusMap.get(id);
      pageStatus.currentPage = currentPage;
      this.pageStatusMap.set(id, pageStatus);
    }

    @action('保存被回复人的签字意见文本') 
    setReplyMark = (text) => {
      this.signReplyText = text;
    }
    @action('保存一级回复')
    saveReplyOthers = (params, callBack) => {
      const { replyInfo={}, richParams } = params;
      let passParams = {};
      let str = richParams.remark;
      if(richParams.remark != '' && richParams.remark.indexOf('<img') < 0) {
        str = richParams.remark.replace(/<\/?[^>]*>/g, '');
        str = str.replace(/[\u200B-\u200D\uFEFF]/g, "");
        str = str.replace(/\n/g,'');
        str = str.replace("&#8203;", "").replace(/&nbsp;/g, '');
        str = str.trim();
      } 
      if (!str) {
        message.destroy();
        message.error(getLabel(382648, '请输入交流内容'));
        return false;
      }
      let newParams = { "reply_man": replyInfo.displayname, 
                        "log_useid": replyInfo.displayid,
                        "log_displaydepid": replyInfo.displaydepid,
                        "log_displaydepname": replyInfo.displaydepname,
                        "log_operatedate": replyInfo.log_operatedate,
                        "log_operatetime": replyInfo.log_operatetime,
                        "log_nodename": replyInfo.log_nodename,
                        "operationname": replyInfo.operationname,
                        "sign_logid": replyInfo.logid,
                        "signReplyText":  this.signReplyText,
                        'log_userType': replyInfo.displaytype == '0' ? '1' : replyInfo.displaytype == '1' ? '2' : ''
                      }
      passParams = { ...newParams, ...richParams,...this.logParams, "quote_type": 'quoteSign','refRequestId':this.refRequestId,'isSubReqeuestid':this.isSubReqeuestid()};
      Api.doSaveContent(passParams).then(res => {
        if(res.result) {
          // this.reflashContentList(replyInfo.logid);
          this.loadMarkInfo(); 
        }
        isFunction(callBack) && callBack();
      })
    }

    //是否其它流程
    isSubReqeuestid = () => {
        let refRequestId = this.refRequestId;
        let allrequestInfos = this.requestLogParams.allrequestInfos;
        for(let index in allrequestInfos){
            if(allrequestInfos[index].requestid == refRequestId){
                return 1 ;
            }
        }
        return 0;
    }

    //删除评论
    delContent = (params,id) => {
      Api.doDelete({...this.logParams,...params}).then(data => {
        if(data.canDelete === false) {
            message.destroy();
            message.error(getLabel('512478','已超过规定时间或有新内容，无法删除'));
            this.loadMarkInfo(); 
        } else {
          this.loadMarkInfo(); 
        }
      })
    }
    @action('保存二级子回复')
    saveReply = (params,logid, callBack) => {
      let newParams = { ...params, refRequestId:this.refRequestId,'isSubReqeuestid':this.isSubReqeuestid(), ...this.logParams};
      Api.doSaveReply(newParams).then(data => {
          if(data.result) {
              this.reflashContentList(logid);
          }
          isFunction(callBack) && callBack();
      })
      
    }

  /**
     * 编辑交流内容
     */
    editContent = (params, logid, callBack) => {
      Api.doEditContent({...this.baseParam,...params}).then(data => {
          if(data.canModify === false){
              message.destroy();
              message.error("已超过规定时间或有新内容，无法编辑！");
          }
          this.reflashContentList(logid);
          isFunction(callBack) && callBack();
      })
  }

    @action('刷新评论内容')
    reflashContentList = (id) => {
      let passParams = {};
      passParams = {type: 'list', requestLogId: id, ...this.logParams,refRequestId:this.refRequestId,'isSubReqeuestid':this.isSubReqeuestid()};
      Api.getContentList(passParams).then( data => {
        let tempArr = cloneDeep(toJS(this.logList));
        tempArr.map( (v,index) => {
          if(v.logid == id) {
            tempArr[index].commentList = [...data.contentList];
            console.log(toJS(tempArr));
          }})
        this.logList = tempArr;
      })
          
    }

    @action
    setState = (params = {}, callBack) => {
        Object.keys(params).forEach(key => {
            this.status[key] = params[key];
        });
        isFunction(callBack) && callBack();
        return this;
    }
    @action('更新请求参数')
    updateLogParams = (params = {}, isLoadLog = false)  => {
        this.logListTabKey > 2 ? this.relLogParams = {...this.relLogParams, ...params} : this.logParams = {...this.logParams, ...params};
        if (isLoadLog) {
            this.loadMarkInfo();
        }
    }

    @action('签字意见高级搜索')
    advanceSearch = () => {
        this.updateLogParams({maxrequestlogid:'',pgnumber:1});
        this.loadMarkInfo();
    }

    @action('修改每页显示数量')
    setLogPagesize = (params = {}) =>  {
        API.updateRequestLogPageSize(params).then(data => {
            let logParamsInit = {
                pgnumber: 1,
                maxrequestlogid: 0,
                wfsignlddtcnt: params.logpagesize
            };
            this.updateLogParams(logParamsInit, true);
        });
    }

    @action('切换tab页')
    changeLogListTab = (key, refRequestId) =>  {
        this.refRequestId = refRequestId;
        this.logListTabKey = key;
    }

    @action
    controllShowUserImg = () =>  {
        this.isShowUserheadimg = !this.isShowUserheadimg;
        API.updateUserTxStatus({txstatus: !this.isShowUserheadimg ? '0' : '1'});
    }

    @action
    loadRefReqSignInfo = (params = {})  => {
        this.relLogParams = {...this.relLogParams, ...params};
        this.loadLogBaseInfo();
    }

    @action
    scrollLoadSign = (params = {})  => {
        this.updateLogParams(params);
        this.loading = true;
        API.getRequestLogList(this.queryLogParams).then(data => {
            const {loglist = [], maxrequestlogid, totalCount} = data;
            const _loglist = concat(mobx.toJS(this.logList), loglist);
            this.setLogData(_loglist, totalCount);
            this.updateLogParams({maxrequestlogid});
            this.setLoging(false);
        });
    }

    @action
    controllSearchDrop = (bool) =>  {
        this.showSearchDrop = bool;
    }

    @action
    clearFormFields = () =>  {
        this.searchForm.resetConditionValue();      //清除查询条件值
    }

    @action setLoging = (bool) =>  {
        this.loading = bool;
    }

    @action setShowUserHeadImg = (bool)  => {
        this.isShowUserheadimg = bool;
    }

    @action setRequestLogParams = (params)  => {
        this.requestLogParams = params;
    }

    @action setLogData = (logList, logCount)  => {
        this.logCount = logCount;
        this.logList = logList;
    }

   

  

    
}